package index;

import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import gitobject.Blob;
import gitobject.Tree;
import repository.Repository;

import java.io.*;
import java.util.LinkedList;

public class Index {
    // 工作区路径
    private static String gitDir= Repository.getGitDir();
    private static String path =  Repository.getGitIndex();
    private static LinkedList<String> indexList = new LinkedList<String>();
    private volatile static Index index;
    private static File indexFile;

    public Index() throws IOException {
        indexFile = new File(path);
        // 暂存区不存在，就创建一个
        if(!indexFile.exists()){
            FileCreation.createFile(gitDir,"index","");
        }
    }

    public static Index getInstance() throws IOException {
        // 双检锁
        if(index==null){
            synchronized ( Index.class ){
                if(index==null){
                    index = new Index();
                }
            }
        }
        return index;
    }

    public String getPath() {
        return path;
    }

    public  LinkedList<String> getIndexList() {
        return indexList;
    }

    public static void setIndexList(LinkedList<String> indexList) {
        Index.indexList = indexList;
    }

    public boolean exist(){ return new File(getPath()).exists(); }

    public boolean compare(Blob blob,File file,String filename) throws Exception {
        for(String item:indexList){
            if(item.equals(blob.indexBlob(file) + filename + file.getName())){
                return false;
            }
        }
        return true;
    }

    private LinkedList<String> addIndexList(String filename, File file) throws Exception {
        if(file.isFile()){
            Blob blob = new Blob(file);
            // 在objects里创建blob对象
            FileCreation.createDirectory(blob.getPath(),blob.genKey(file).substring(0,2));
            FileCreation.createFile(blob.getPath()+File.separator+blob.genKey(file).substring(0,2),blob.genKey(file).substring(2),"");
            // 写入
            blob.compressWrite();
            // 加入list
            // blob.indexBlob(file): 10064 fmt blob.key (51)
            if(compare(blob,file,filename)){
                filename=filename.equals("")?"":filename+"\\";
                indexList.add(blob.indexBlob(file) + filename + file.getName());
                System.out.print("Add Successfully:");
                System.out.println(blob.indexBlob(file) + filename + file.getName());
            }else{
                System.out.println("Add Failed. There Is A Same File In Index !");
            }
        }else if (file.isDirectory()){
            // 取出文件夹的文件
            File[] fs = file.listFiles();
            // 先判断是不是空文件夹，为空时不做处理
            if(fs.length>0){
                Tree tree = new Tree(file);
                // 在objects里创建tree
                FileCreation.createDirectory(tree.getPath(),tree.getKey().substring(0,2));
                FileCreation.createFile(tree.getPath()+File.separator+tree.getKey().substring(0,2),tree.getKey().substring(2),"");
                tree.compressWrite();
                for (File f : fs) {
                    if (filename.equals("")) {
                        addIndexList(file.getName(),f);
                    }else{
                        addIndexList(filename+File.separator+file.getName(),f);
                    }
                }
            }else{
                System.out.println("Empty Directory");
            }
        }
        return indexList;
    }

    public void addBlobs(String filename,File file) throws Exception {
        // 将add对象进行处理后，加入list
        indexList = addIndexList(filename,file);
        // 将本次list的内容写入index
        saveIndexObj();
    }

    public void saveIndexObj() throws IOException {
        FileWriter fw = new FileWriter(indexFile);
        for (String s : indexList) {
            fw.write(s + "\n");
        }
        fw.flush();
        fw.close();
    }

    public static void printIndex() throws IOException {
        for(String item:indexList){
            System.out.println(item);
        }
    }

    // 清空暂存区
    public void clearIndex(){
        FileDeletion.deleteContent(indexFile);
    }

    // 找到文件下标
    public int findTarget(String filename){
        for(int i = 0 ; i<indexList.size() ; i++){
            if(indexList.get(i).substring(53).equals(filename)){
                return i;
            }
        }
        return -1;
    }

    public void removeIndexObj(String filename){
        int targetIndex = findTarget(filename);
        System.out.print(filename);
        // 确定文件存在后删除
        if(targetIndex!=-1){
            indexList.remove(targetIndex);
            System.out.println(" : Remove Successfully!");
        }else{
            System.out.println(" : Remove Failed!");
        }
    }
}